<?php
/**
 * 公共函数文件
 * @author Jerry
 * @version 1.0
 */

/**
 * 随机返回数组中的一个值
 * @author hary
 * @param Array $arr
 * @return string $val
 */
function get_one_by_array( $arr )
{
	if(is_array($arr))
	{
		$key = array_rand( $arr );

		$val = $arr[$key];
	}
	else
	{
		$val = $arr;
	}

	return $val;
}

/**
 * 
 * @param $dirname
 * @return unknown_type
 */
function rmdir_rf($dirname) {
   if ($dirHandle = opendir($dirname)) {
   	   $old_cwd = getcwd();
       chdir($dirname);
       while ($file = readdir($dirHandle)) {
           if ($file == '.' || $file == '..') continue;
           if (is_dir($file)) rmdir_rf($file);
           else unlink($file);
       }
       closedir($dirHandle);
       chdir($old_cwd);
       rmdir($dirname);
   }
}

function full_rmdir($dirname){
       if ($dirHandle = opendir($dirname)){
           $old_cwd = getcwd();
           chdir($dirname);

           while ($file = readdir($dirHandle)){
               if ($file == '.' || $file == '..') continue;

               if (is_dir($file)){
                   if (!full_rmdir($file)) return false;
               }else{
                   if (!unlink($file)) return false;
               }
           }

           closedir($dirHandle);
           chdir($old_cwd);
           if (!rmdir($dirname)) return false;

           return true;
       }else{
           return false;
       }
   }



/**
 * 页面跳转
 */
function __redirect($url,$arg = null)
{

	$arg = array_merge(array('url_pre'=>$_SESSION['pay']['url_pre']),$arg);

	Goto($url.'?'.http_build_query($arg),'header','document',false);

}

/**
 * 根据用户的ip获取用户的地址信息
 *
 * @param $ip			用户ip
 * @return array			用户地址数据
 * @author 				hary
 * e.g
 * array (
 * 'result' => 0,
 * 'desc' => 'OK',
 * 'country_en' => 'IA',
 * 'country_cn' => 'IA保留地址', 
 * 'area' => NULL, 'province_id' => 0,
 * 'province_code' => 0,
 * 'province_name' => 'Internet保留(可能是内网)', 
 * )
 */
function getInfoByIp($ip)
{
	global $sys_conf_var;

	if(isset($ip) && strlen($ip) >= strlen("0.0.0.0") )
	{

		$content = file_get_contents(get_one_by_array($sys_conf_var['ipservice']['server']) ."query_info.php?&auth=".$sys_conf_var['ipservice']['auth_key']."&query_ip=".$ip);
	}

	$result = array();

	@eval("\$result={$content};");

	return $result;
}


/**
 * 根据省级获取市级列表
 * @param $prov_id
 * @return array
 */
function getCitysByPid( $prov_id )
{
	global $sys_conf_var;
	 
	$ret = array();

	foreach ( $sys_conf_var['pay']['arr_city'] AS $code => $name )
	{
		if ( belongProvince( $code, $prov_id ) )
		{
			$ret[$code] = $name;

		}
	}

	return $ret;
}

/**
 * 截取字符串
 * @param $city_id
 * @param $prov_id
 * @return unknown_type
 */
function belongProvince( $city_id, $prov_id )
{
	$city_mark = substr( $city_id, 0, 2 );
	$prov_mark = substr( $prov_id, 0, 2 );

	if ( $city_mark == $prov_mark )
	{
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}



/**
 * 解析调式信息,得到客户段信息,如IP等
 */
function parse_incoming()
{
	global $_GET, $_POST, $HTTP_CLIENT_IP, $REQUEST_METHOD, $REMOTE_ADDR, $HTTP_PROXY_USER, $HTTP_X_FORWARDED_FOR;
	$return = array();

	if( is_array($_GET) )
	{
		while( list($k, $v) = each($_GET) )
		{
			if( is_array($_GET[$k]) )
			{
				while( list($k2, $v2) = each($_GET[$k]) )
				{
					$return[$k][ clean_key($k2) ] = clean_value($v2);
				}
			}
			else
			{
				$return[$k] = clean_value($v);
			}
		}
	}

	// Overwrite GET data with post data

	if( is_array($_POST) )
	{
		while( list($k, $v) = each($_POST) )
		{
			if ( is_array($_POST[$k]) )
			{
				while( list($k2, $v2) = each($_POST[$k]) )
				{
					$return[$k][ clean_key($k2) ] = clean_value($v2);
				}
			}
			else
			{
				$return[$k] = clean_value($v);
			}
		}
	}

	//----------------------------------------
	// Sort out the accessing IP
	// (Thanks to Cosmos and schickb)
	//----------------------------------------

	$addrs = array();

	foreach( array_reverse( explode( ',', $HTTP_X_FORWARDED_FOR ) ) as $x_f )
	{
		$x_f = trim($x_f);

		if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $x_f ) )
		{
			$addrs[] = $x_f;
		}
	}

	$addrs[] = $_SERVER['REMOTE_ADDR'];
	$addrs[] = $HTTP_PROXY_USER;
	$addrs[] = $REMOTE_ADDR;
	//header("Content-type: text/plain"); print_r($addrs); print $_SERVER['HTTP_X_FORWARDED_FOR']; exit();

	$return['IP_ADDRESS'] = select_var( $addrs );

	// Make sure we take a valid IP address

	$return['IP_ADDRESS'] = preg_replace( "/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/", "\\1.\\2.\\3.\\4", $return['IP_ADDRESS'] );

	$return['request_method'] = ( $_SERVER['REQUEST_METHOD'] != "" ) ? strtolower($_SERVER['REQUEST_METHOD']) : strtolower($REQUEST_METHOD);
	$data = explode(';',$return[op]);
	foreach($data as $key=>$var)
	{
		$data1 = explode('::', $var);
		$return["{$data1[0]}"] = $data1[1];
	}
	//debug($return);

	return $return;
}


function clean_key($key)
{

	if ($key === "")
	{
		return "";
	}
	$key = preg_replace( "/\.\./"           , ""  , $key );
	$key = preg_replace( "/\_\_(.+?)\_\_/"  , ""  , $key );
	$key = preg_replace( "/^([\w\.\-\_]+)$/", "$1", $key );
	return $key;
}

function clean_value($val)
{

	if ($val == "")
	{
		return "";
	}

	if ( get_magic_quotes_gpc() )
	{
		$val = stripslashes($val);
	}

	return $val;
}

function select_var($array) {

	if ( !is_array($array) ) return -1;

	ksort($array);


	$chosen = -1;  // Ensure that we return zero if nothing else is available

	foreach ($array as $k => $v)
	{
		if (isset($v))
		{
			$chosen = $v;
			break;
		}
	}

	return $chosen;
}

function add_slashes($string)
{
	if(!$GLOBALS['magic_quotes_gpc'])
	{
		if(is_array($string))
		{
			foreach($string as $key => $val)
			{
				$string[$key] = add_slashes($val);
			}
		}
		else
		{
			$string = addslashes($string);
		}
	}
	return $string;
}

/**
 * 显示调式信息
 */
function debug($str = '')
{
	global $db,$in_var,$logger;

	echo '<br>';
	print_r($in_var);
	echo "<br>Time : " . $logger->dumpTime();

	if($db) echo $db->logger->dumpQueries();

	if($str)
	{
		echo '<hr>';
		print_r($str);
	}

}


/**
 * @return unknown_type
 */
function tpl_debug()
{
	global $tpl;

	print_r($tpl->tpl_vars);
}

/**
 * @param $message
 * @param $url_forward
 * @param $delay
 * @param $js
 * @param $close
 * @return unknown_type
 */
function show_message($message, $url_forward = '',$delay = '0', $js = '', $close = '')
{

	if($js == 'confirm')
	{
		$message = "<script>\n"
		. "if(confirm(\"" . $message
		. "  是否返回？\")) parent.location=\""
		. $url_forward
		. "\"\n"
		."</script>\n";

		echo $message;
		exit;
	}
	elseif($js == 'alert')
	{
		if($close)
		{
			$message = "<script>alert(\""
			. $message . "窗口自动关闭\")\n"
			. "window.self.close()\n"
			. "</script>";
		}
		else
		{
			$message = "<script>alert(\"" . $message . "\")\n"
			."document.location='" . $url_forward . "'\n"
			."</script>";
		}

		echo $message;
		exit;
	}
	else
	{
		global $tpl,$admin_lang;

		$tpl->assign('Delay',$delay);
		$tpl->assign('UrlForward',$url_forward);
		$tpl->assign('Message',$message);
		$tpl->display('sys_error.html');
		//exit;
	}
}

/**
 *
 * @param $url
 * @param $type
 * @param $target
 * @param $referer 是否附加referer字符串
 * @return unknown_type
 */
function goto($url,$type = 'js',$target = 'document',$referer = true)
{
	if ($referer)
	{
		$url = make_url($url,'referer',rawurlencode($_SERVER['REQUEST_URI']));
	}

	if($type == 'header')
	{
		header("location: " . $url);
		exit;
	}
	elseif($type == 'js')
	{
		echo "<script>" . $target . ".location='" . $url . "'\n" . "</script>";
		exit;
	}
}

/**
 * @param $page_num
 * @param $current_page
 * @param $send_var
 * @param $item_num
 * @return unknown_type
 */
function page($page_num,$current_page,$send_var,$item_num = 5)
{
	global $admin_lang;

	if($page_num == '') return false;

	$header = floor(($current_page - 1)/$item_num);

	$start = $header*$item_num + 1;

	for($i= $start;$i<=$start + ($item_num - 1);$i++)
	{
		$link = str_replace("{Page}", $i,$send_var);

		if($current_page == $i)
		{
			$page.= "<b>".$i."</b>&nbsp;";
		}
		else
		{
			$page.= "<a href='".$link."'>[".$i."]</a>&nbsp;";
		}

		$pages[] = array('page_num'=>$i,'page_link'=>$link);

		if($i==$page_num) break;
	}

	if ($current_page < $page_num)
	{
		$link1= str_replace("{Page}", $current_page+1 ,$send_var);
		$page = $page . "&nbsp;<b><a href='".$link1."' >下一页</a></b>";

		$next_url = $link1;
	}

	if($current_page > 1) {
		if(($current_page-1) == 0)
		$link1 = str_replace("{Page}", 0,$send_var);
		else
		$link1= str_replace("{Page}" , $current_page-1 ,$send_var);
		$page= "<b><a href='".$link1."' >上一页</a></b>&nbsp;&nbsp;".$page;

		$previous_url = $link1;
	}

	if((($start + $item_num)) <= $page_num) {
		$i =  $start + $item_num;
		$link = str_replace("{Page}", $i,$send_var);
		$page= $page."&nbsp;&nbsp;<b><a href='".$link."' >下十页</a></b>";

		$next_10_url = $link;
	}

	if(($start - 1) > 0)
	{
		$i =  $start - $item_num;
		$link = str_replace("{Page}", $i,$send_var);
		$page= "<b><a href='".$link."' >上十页</a></b>&nbsp;&nbsp;".$page;

		$previous_10_url = $link;
	}



	return array('page' => $page , 'pages' => $pages , 'next_url' => $next_url , 'previous_url' => $previous_url , 'next_more_url' => $next_10_url , 'previous_more_url' => $previous_10_url );

}



/**
 * @param $str
 * @param $start
 * @param $end
 * @param $sss
 * @return unknown_type
 */
function CsubStr($str,$start,$end,$sss='...') {
	/*
	 UTF-8 version of substr(), for people who can't use mb_substr() like me.
	 Length is not the count of Bytes, but the count of UTF-8 Characters

	 Author: Windix Feng
	 Bug report to: windix(AT)263.net, http://www.douzi.org/blog

	 - History -
	 1.0 2004-02-01 Initial Version
	 2.0 2004-02-01 Use PREG instead of STRCMP and cycles, SPEED UP!
	 */
	preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $str, $ar);

	if(func_num_args() >= 3)
	{
		$end = func_get_arg(2);
		if(count($ar[0])>$end)
		{
			$str = join("",array_slice($ar[0],$start,$end)).$sss;
		}
		else
		{
			$str = $str;
		}
	}
	else
	{
		$str = join("",array_slice($ar[0],$start)).$sss;
	}

	$patt = "/(<[^>]*\.\.\.)/";
	preg_match_all($patt, $str, $matches);
	$replace_str = $matches[1][0];
	$str = str_replace($replace_str, "...", $str);

	return $str;
}


//高亮关键字
function HighLight($Content,$KeyWords,$Num = '')
{
	$HighLightKeyWords = "<font color=red>$KeyWords</font>";
	$Content = str_replace($KeyWords,$HighLightKeyWords,$Content);
	if(!empty($Num)){
		$Content = CsubStr($Content,$Num);
	}
	return $Content;


}


/**
 * @param $dir
 * @return unknown_type
 */
function deldir($dir)
{
	$dh = opendir($dir);

	while ($file=readdir($dh))
	{
		if($file!="." && $file!="..")
		{
			$fullpath=$dir."/".$file;
			if(!is_dir($fullpath))
			{
				unlink($fullpath);
			} else
			{
				deldir($fullpath);
			}
		}
	}

	closedir($dh);

	if(rmdir($dir))
	{
		return true;
	}
	else
	{
		return false;
	}
}

//缩略图片
function AutoImg($srcFile,$toW="120",$toH="160",$toFile="../upload/tmp/")
{
	global $html , $sys_conf_var;

	if(!is_dir($toFile)){
		$html->createdir($toFile);
	}

	if($toFile==""){ $toFile = $srcFile; }
	else
	{
		$file_type = explode('.',$srcFile);
		$cdn_url = $sys_conf_var['server']['cdn'] . "/upload/tmp/" . md5($srcFile . $toW . $toH) . '.' . end($file_type);

		if(is_file($toFile = $toFile . md5($srcFile . $toW . $toH) . '.' . end($file_type)))
		{
			return $cdn_url;
		}
	}

	$info = "";
	$data = GetImageSize($srcFile,$info);

	switch ($data[2])
	{
		case 1:
			if(!function_exists("imagecreatefromgif")){
				echo "你的GD库不能使用GIF格式的图片，请使用Jpeg或PNG格式！";
				exit();
			}
			$im = ImageCreateFromGIF($srcFile);
			break;
		case 2:
			if(!function_exists("imagecreatefromjpeg")){
				echo "你的GD库不能使用jpeg格式的图片，请使用其它格式的图片！";
				exit();
			}
			$im = ImageCreateFromJpeg($srcFile);
			break;
		case 3:
			$im = ImageCreateFromPNG($srcFile);
			break;
		case 6:
			return $srcFile;
			break;
	}

	$srcW=ImageSX($im);
	$srcH=ImageSY($im);

	/*if($srcW > $srcH)
	 {
	 $ftoH = $toH;
	 $ftoW = $srcW * ($toH/$srcH);
	 }
	 else
	 {
	 $ftoW = $toW;
	 $ftoH = $srcH * ($toW/$srcW);
	 }*/
	$ftoH = $toH;
	$ftoW = $srcW * ($toH/$srcH);

	if($ftoW < $toW)
	{
		$ftoH = $ftoH * ($toW/$ftoW);
		$ftoW = $toW;
	}
	/*$toWH=$toW/$toH;
	 $srcWH=$srcW/$srcH;
	 if($toWH<=$srcWH){
	 $ftoW=$toW;
	 $ftoH=$ftoW*($srcH/$srcW);
	 }
	 else{
	 $ftoH=$toH;
	 $ftoW=$ftoH*($srcW/$srcH);
	 }    */

	if($srcW>$toW||$srcH>$toH)
	{
		if(function_exists("imagecreatetruecolor")){
			$ni = ImageCreateTrueColor($toW,$toH);
			if($ni) ImageCopyResampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
			else{
				$ni=ImageCreate($toW,$toH);
				ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
			}
		}else{
			$ni=ImageCreate($toW,$toH);
			ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
		}

		if(function_exists('imagejpeg')) ImageJpeg($ni,$toFile,100);
		else ImagePNG($ni,$toFile);
		ImageDestroy($ni);
	}
	else
	{
		return $srcFile;
	}

	ImageDestroy($im);

	//return $toFile;
	return $cdn_url;
}

/**
 * @param $className
 * @return unknown_type
 */
function __autoload($className)
{
	if (file_exists(CLASS_DIR . strtolower($className) . '.class.php'))
	{
		require_once(CLASS_DIR. strtolower($className) . '.class.php');
	}
	else if (file_exists(CONTROLLER_DIR . strtolower($className) . '.class.php'))
	{
		require_once(CONTROLLER_DIR . strtolower($className) . '.class.php');
	}
	else if (file_exists(MODEl_DIR . strtolower($className) . '.class.php'))
	{
		require_once(MODEl_DIR . strtolower($className) . '.class.php');
	}
	else
	{
		/* Error Generation Code Here */
	}
}

/**
 * @param $msg
 * @return unknown_type
 */
function show_error_msg($msg)
{
	echo '<div id="error_msg">' . $msg . '</div>';
}

/**
 * @param $num
 * @return unknown_type
 */
function fotmat_bit($num)
{
	$bitunit = array(' B',' KB',' MB',' GB');
	for($key=0;$key<count($bitunit);$key++){
		if($num>=pow(2,10*$key)-1){ //1023B 会显示为 1KB
			$num_bitunit_str=(ceil($num/pow(2,10*$key)*100)/100)." $bitunit[$key]";
		}
	}
	return $num_bitunit_str;
}

/**
 * php DES解密函数
 *
 * @param string $key 密钥
 * @param string $encrypted 加密字符串
 * @return string
 */
function des_decode($key,$encrypted)
{
	$encrypted = base64_decode($encrypted);

	$td = mcrypt_module_open(MCRYPT_DES,'',MCRYPT_MODE_CBC,''); //使用MCRYPT_DES算法,cbc模式
	$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
	$ks = mcrypt_enc_get_key_size($td);

	mcrypt_generic_init($td, $key, $key);       //初始处理

	$decrypted = mdecrypt_generic($td, $encrypted);       //解密

	mcrypt_generic_deinit($td);       //结束
	mcrypt_module_close($td);

	$y = pkcs5_unpad($decrypted);

	return $y;
}

/**
 * php DES加密函数
 *
 * @param string $key 密钥
 * @param string $text 字符串
 * @return string
 */
function des_encode($key,$text)
{
	$y = pkcs5_pad($text);

	$td = mcrypt_module_open(MCRYPT_DES,'',MCRYPT_MODE_CBC,''); //使用MCRYPT_DES算法,cbc模式
	$ks = mcrypt_enc_get_key_size($td);

	mcrypt_generic_init($td, $key, $key);       //初始处理

	$encrypted = mcrypt_generic($td, $y);       //解密

	mcrypt_generic_deinit($td);       //结束
	mcrypt_module_close($td);

	return base64_encode($encrypted);
}

/**
 * @param $text
 * @param $block
 * @return unknown_type
 */
function pkcs5_pad($text,$block=8)
{
	$pad = $block - (strlen($text) % $block);
	return $text . str_repeat(chr($pad), $pad);
}


/**
 * @param $text
 * @return unknown_type
 */
function pkcs5_unpad($text)
{
	$pad = ord($text{strlen($text)-1});

	if ($pad > strlen($text)) return $text;
	if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return $text;
	return substr($text, 0, -1 * $pad);
}
/**
 * 这个函数可以传入多个参数，前两个参数是显示的提示信息和默认跳转路径
 * 以后的参数以以下格式传入：$text：显示的链接文本，$url：点击后跳转的路径
 * 如果参数不为偶数，则忽略最后一个。
 * @example show_choices('添加成功',get_url('game','addCate'),5,'<b>继续添加</b>',get_url('game','addCate'),'返回列表',get_url('game','showCateList'));
 * @param $message 显示信息
 * @param $defaultUrl 默认跳转路径
 * @param $waittime = 5 跳转待时间
 * @return unknown_type
 */
function show_choices($message,$defaultUrl='javascript:history.back()',$waittime = 5,$title1='快速返回')
{
	$num = func_num_args();
	$args = func_get_args();

	if ($num < 5)
	{
		try
		{
			$args[1] = func_get_arg(1) ? func_get_arg(1) : $defaultUrl;
			$args[2] = func_get_arg(2) ? func_get_arg(2) : $waittime;
			$args[3] = func_get_arg(3) ? func_get_arg(3) : $title1;
			$args[4] = func_get_arg(4) ? func_get_arg(4) : $defaultUrl;
		}catch(Exception $e)
		{

		}
		$num = 5;
	}

	if($num % 2 != 1){
		array_pop($args);
		$num --;
	}

	$choices = array();

	for($i = 3;$i<$num;$i+=2){
		$choices[] = array('text'=>$args[$i],'url'=>$args[$i + 1]);
	}

	global $tpl;

	$tpl->assign('choices',$choices);
	$tpl->assign('message',$message);
	$tpl->assign('waittime',$waittime);
	$tpl->assign('defaultUrl',$defaultUrl);

	$tpl->template_dir = SYS_PATH . 'template/result/';

	$tpl->display('error.html');exit;
}

/**
 * @param $str
 * @return unknown_type
 */
function replace_cdn_url($str)
{
	global $sys_conf_var;

	$str = str_replace('html/upload/game',$sys_conf_var['img']['cdn'] . '/game',$str);
	//$str = str_replace('html/upload/video',$sys_conf_var['img']['cdn'] . 'html/upload/video',$str);
	$str = str_replace($sys_conf_var[ 'upload' ][ 'blocks' ],$sys_conf_var['img']['cdn'] . '/img/da/blocks/',$str);
	$str = str_replace($sys_conf_var['upload']['medal'],$sys_conf_var['img']['cdn'] . '/img/da/medals/',$str);
	$str = str_replace($sys_conf_var['upload']['attire'],$sys_conf_var['img']['cdn'] . '/img/da/attire/',$str);
	$str = str_replace($sys_conf_var['upload']['zk_type'],$sys_conf_var['img']['cdn'] . '/img/da/zk_type/',$str);

	return $str;
}

/**
 * judge if a string starts with the certain segment.
 * @param $segment a short string
 * @param $string full string
 * @return bool
 */
function starts_with($segment,$string)
{

	return strpos($string,$segment) === 0;

}
/**
 * 非强制上传文件.
 * @param $form_name 文件域的名字
 * @param $new_file_name 新文件名字
 * @param $exts 文件扩展名列表
 * @param $dir 文件存储目录
 * @param $upload_obj 文件上传对象
 * @return bool | string false:没有上传文件,string:新文件名
 */
function upload_file($form_name,$new_file_name,$exts,$dir,$upload_obj)
{
	if (array_key_exists($form_name,$_FILES) && is_uploaded_file($_FILES[$form_name]['tmp_name']))
	{
		$new_file_name = empty($new_file_name) ? md5(time() + mt_rand(1,15))  : $new_file_name;

		$upload_obj->init(20971520,$exts);
		$upload_obj->setUploadFileName($new_file_name);
		$upload_obj->setUploadDir($dir);

		if(!$upload_obj->uploadFile($form_name))
		{
			return false;
		}

		$ext = end(explode('.',$_FILES[$form_name]['name']));

		return strtolower($new_file_name . '.' . $ext);
	}
	return false;
}
/**
 * 产生一个根据日期和时间计算出来的文件名,不包含扩展名
 * @return string
 */
function get_filename_by_time()
{
	return date('Y_m_d_H_i_s_') . substr(microtime(),2,2);
}
/**
 * 增强版的mkdir
 * @param $dir
 * @param $mode
 * @return unknown_type
 */
function mk_dir($dir, $mode = 0755)
{
	if (is_dir($dir) || @mkdir($dir,$mode)) return true;
	if (!mk_dir(dirname($dir),$mode)) return false;
	return @mkdir($dir,$mode);
}

/**
 * @param $d
 * @param $vid
 * @return unknown_type
 */
function getClientVideoURI( $d='index', $vid='' )
{
	$uri = "/client.php?c=video&d={$d}";
	if( !empty( $vid ) )
	{
		$uri .= "&vid={$vid}";
	}
	return $uri;
}

/**
 * @param $d
 * @param $vid
 * @return unknown_type
 */
function getClientGameURI( $d='index', $vid='' )
{
	$uri = "/client.php?c=game&d={$d}";
	if( !empty( $vid ) )
	{
		$uri .= "&vid={$vid}";
	}
	return $uri;
}

/**
 * @param $d
 * @param $vid
 * @return unknown_type
 */
function getWebVideoURI( $d, $vid='' )
{
	if ( !empty( $vid ))
	{
		return get_url('video', $d, "vid={$vid}");
	}
	else
	{
		return get_url('video', $d);
	}
}

/**
 * @param $d
 * @return unknown_type
 */
function getRegisterURI( $d='register' )
{
	return get_url('account', $d);
}

/**
 * @param $d
 * @return unknown_type
 */
function getLoginURI( $d='login' )
{
	return get_url('account', $d);
}

/**
 * @param $d
 * @return unknown_type
 */
function getLogoutURI( $d='logout' )
{
	return get_url('account', $d);
}

/**
 * @param $d
 * @return unknown_type
 */
function getWebGameURI( $d='index' )
{
	return get_url('game', $d);
}

/**
 * 简化的ini解析
 * 注释:必须在行首以 ; 开始
 * 名值对:以 = 分隔,不管其他
 * @param $file_name
 * @return unknown_type
 */
function parse_ini($file_name)
{
	$lines = file($file_name);
	$ini = array();
	foreach ($lines as $line)
	{
		if ($line{0} == ';') continue;
		if (strpos($line,'=') === false) continue;
		$line1 = explode('=',$line,2);
		if (empty($line1[0])) continue;
		$ini[ trim($line1[0]) ] = trim($line1[1]);
	}

	return $ini;
}

/**
 * 记录日志
 * @author Henry <henry@taomee.com>
 * @param int $type
 * @param array $data_array
 */
function msglog($type, $data_array)
{
	// modified by Rox, auto get log_file and timestamp
	global $sys_conf_var;
	$log_file = MSGLOG_LOG_PATH;
	$timestamp = time();

	if(count($data_array) <= 0)
	{
		return false;
	}
	$len = 24;
	$hlen = 24;
	$flag0 = 0;
	$flag = 0;
	$saddr = 0;
	$seqno = 0;

	$packed_body = "";
	foreach($data_array as $data_row)
	{
		$packed_body .= pack("L",$data_row);
		$len += 4;
	}

	$packed_header = pack("SCCL5",$len,$hlen,$flag0,$flag,$saddr,$seqno,$type,$timestamp);
	$packed_data = $packed_header . $packed_body;

	//write to stat log file
	umask(0000);
	$log_file_fd = fopen($log_file,"ab");
	if(!$log_file_fd)
	{
		return false;
	}
	chmod($log_file, 0777);
	if(!fwrite($log_file_fd,$packed_data))
	{
		return false;
	}

	fclose($log_file_fd);
	return true;
}

/**
 * 判断用户是否是 NPC
 * @param $uid
 */
function is_npc($uid)
{
	$uid = intval($uid);

	return ( $uid && $uid >= 10000 && $uid < 20000 );
}


function ip2long_improve($ip)
{
	$ip_arr = explode('.',$ip);
	$iplong  = (16777216 * intval($ip_arr[0]));
	$iplong += (65536 * intval($ip_arr[1])) + (256 * intval($ip_arr[2]));
	$iplong += intval($ip_arr[3]);
	return $iplong;
}

function tidy_html($str)
{
	if ( !class_exists('tidy') )
	{
		return $str;
	}

	// Specify configuration
	$config = array(
        'indent'         => true,
        'output-xhtml'   => false,
        'wrap'           => 200,
        'show-warnings'  => false,
        'tab-size'       => 2,
	);

	// Tidy
	$tidy = new tidy;
	$tidy->parseString($str, $config, 'utf8');
	$tidy->cleanRepair();

	// Output
	return $tidy;
}

/*********************************************/
/* Fonction: ImageCreateFromBMP              */
/* Author:   DHKold                          */
/* Contact:  admin@dhkold.com                */
/* Date:     The 15th of June 2005           */
/* Version:  2.0B                            */
/*********************************************/

function ImageCreateFromBMP($filename)
{
	//Ouverture du fichier en mode binaire
	if (! $f1 = fopen($filename,"rb")) return FALSE;

	//1 : Chargement des ent�tes FICHIER
	$FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
	if ($FILE['file_type'] != 19778) return FALSE;

	//2 : Chargement des ent�tes BM
	$BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
                 '/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
                 '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
	$BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
	if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
	$BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
	$BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
	$BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
	$BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
	$BMP['decal'] = 4-(4*$BMP['decal']);
	if ($BMP['decal'] == 4) $BMP['decal'] = 0;

	//3 : Chargement des couleurs de la palette
	$PALETTE = array();
	if ($BMP['colors'] < 16777216)
	{
		$PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
	}

	//4 : Cr�ation de l'image
	$IMG = fread($f1,$BMP['size_bitmap']);
	$VIDE = chr(0);

	$res = imagecreatetruecolor($BMP['width'],$BMP['height']);
	$P = 0;
	$Y = $BMP['height']-1;
	while ($Y >= 0)
	{
		$X=0;
		while ($X < $BMP['width'])
		{
			if ($BMP['bits_per_pixel'] == 24)
			$COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
			elseif ($BMP['bits_per_pixel'] == 16)
			{
				$COLOR = unpack("n",substr($IMG,$P,2));
				$COLOR[1] = $PALETTE[$COLOR[1]+1];
			}
			elseif ($BMP['bits_per_pixel'] == 8)
			{
				$COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
				$COLOR[1] = $PALETTE[$COLOR[1]+1];
			}
			elseif ($BMP['bits_per_pixel'] == 4)
			{
				$COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
				if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
				$COLOR[1] = $PALETTE[$COLOR[1]+1];
			}
			elseif ($BMP['bits_per_pixel'] == 1)
			{
				$COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
				if     (($P*8)%8 == 0) $COLOR[1] =  $COLOR[1]        >>7;
				elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
				elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
				elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
				elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
				elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
				elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
				elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
				$COLOR[1] = $PALETTE[$COLOR[1]+1];
			}
			else
			return FALSE;
			imagesetpixel($res,$X,$Y,$COLOR[1]);
			$X++;
			$P += $BMP['bytes_per_pixel'];
		}
		$Y--;
		$P+=$BMP['decal'];
	}

	//Fermeture du fichier
	fclose($f1);

	return $res;
}
